import random
import json
from .openai_model import OpenAIModel

class QuestionGenerator:
    """题目生成器类"""
    def __init__(self, knowledge_manager):
        self.knowledge_manager = knowledge_manager
        self.ai_model = OpenAIModel()
        
        # 题目模板（作为备选方案）
        self.question_templates = {
            "math": {
                "addition": {"template": "{a} + {b} = ?", "difficulty": 1},
                "subtraction": {"template": "{a} - {b} = ?", "difficulty": 1},
                "multiplication": {"template": "{a} × {b} = ?", "difficulty": 2}
            },
            "chinese": {
                "pinyin": {"template": "'你好'的拼音是？", "difficulty": 1},
                "idiom": {"template": "'一举两得'的意思是？", "difficulty": 2},
                "synonym": {"template": "下列哪个词与其他三个意思不同？", "difficulty": 1}
            }
        }
    
    def generate_question(self, knowledge_point_id, selected_kps):
        """生成题目"""
        # 只使用AI模型生成题目
        ai_question = self._generate_with_ai(knowledge_point_id)
        return ai_question
    
    def _generate_with_ai(self, knowledge_point_id):
        """使用AI模型生成题目"""
        # 获取知识点名称
        kp_name = "未知知识点"
        for grade in self.knowledge_manager.knowledge_points.values():
            for subject in grade.values():
                for kp in subject:
                    if kp["id"] == knowledge_point_id:
                        kp_name = kp["name"]
                        # 判断科目类型
                        subject_type = "math" if "math" in kp["id"] else "chinese"
                        break
                else:
                    continue
                break
            else:
                continue
            break
        
        # 构建提示词
        if subject_type == "math":
            prompt = f"为小学生生成一道关于'{kp_name}'的数学选择题，包含4个选项（A、B、C、D），其中只有一个正确答案。请以JSON格式返回，包含text（题目内容）、options（选项字典，键为A/B/C/D，值为选项内容）、correct_answer（正确选项）、explanation（答案解释）。"
        else:
            prompt = f"为小学生生成一道关于'{kp_name}'的语文选择题，包含4个选项（A、B、C、D），其中只有一个正确答案。请以JSON格式返回，包含text（题目内容）、options（选项字典，键为A/B/C/D，值为选项内容）、correct_answer（正确选项）、explanation（答案解释）。"
        
        # 调用AI模型
        try:
            response = self.ai_model.generate_text(prompt)
            if response:
                # 解析JSON响应
                if response.startswith("```json") and response.endswith("```"):
                    response = response[7:-3].strip()
                
                result = json.loads(response)
                result["knowledge_point_id"] = knowledge_point_id
                return result
        except Exception as e:
            print(f"AI生成题目失败: {e}")
        
        return None
    
    
    def select_knowledge_point(self, selected_kps, learning_memory):
        """根据学习情况选择知识点"""
        # 如果只有一个知识点，直接返回
        if len(selected_kps) == 1:
            return selected_kps[0]
        
        # 计算每个知识点的正确率
        kp_accuracies = {kp_id: learning_memory.get_accuracy(kp_id) for kp_id in selected_kps}
        
        # 按正确率排序，优先选择正确率低的知识点
        sorted_kps = sorted(kp_accuracies.items(), key=lambda x: x[1])
        
        # 基于正确率分配权重，正确率越低的权重越高
        weights = [max(0.1, 1 - acc) for _, acc in sorted_kps]
        total_weight = sum(weights)
        normalized_weights = [w/total_weight for w in weights]
        
        # 根据权重随机选择一个知识点
        r = random.random()
        cumulative_weight = 0
        for i, weight in enumerate(normalized_weights):
            cumulative_weight += weight
            if r <= cumulative_weight:
                return sorted_kps[i][0]
        
        # 兜底返回第一个知识点
        return selected_kps[0]